// Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
//
// This file is part of FileBow.
//
// FileBow is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// FileBow is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FileBow.  If not, see <http://www.gnu.org/licenses/>.

// Common macros and functions.

#ifndef FILEBOW_COMMON_H__
#define FILEBOW_COMMON_H__

#include <sstream>
#include <string>
#include <vector>

////////////////////////////////////////////////////////////////////////////////
// Common macros.
////////////////////////////////////////////////////////////////////////////////

/**
 * Allows logging using stream operator << and log level.
 * Log level should be one of LogLevel values without leading 'L':
 * DBG, INFO, WARN, ERR.
 */
#define LOG(level) LogStream(LogLevel::L##level, __FILE__, __LINE__)

/**
 * Logs and throws runtime_error when the condition is not satisfied.
 */
#define MCHECK(condition, text) \
  (condition) || LOG(ERR).SetFatal(text) \
      << text << ": " << #condition

/** Standard check. */
#define CHECK(condition) MCHECK(condition, "Check failed")

/** Check for not null pointers. */
#define CHECK_PTR(p) CHECK(p != NULL)

/** Check for null pointers. */
#define CHECK_NULL(p) CHECK(p == NULL)

/** Makes copy and assign operator private. */
#define DISALLOW_COPY(cls) \
  private: cls(const cls&); \
  private: cls& operator =(const cls&);

/** Declares default constructor/destructor and disallow copy. */
#define DECLARE_DEFAULTS(cls) \
  public: cls(); \
  public: virtual ~cls(); \
  DISALLOW_COPY(cls)
#define DEFINE_DEFAULTS(cls) \
  cls::cls() {} \
  cls::~cls() {}

////////////////////////////////////////////////////////////////////////////////
// LogStream.
////////////////////////////////////////////////////////////////////////////////

/**
 * Supported log levels enumeration.
 */
class LogLevel {
  public: enum Value {
    // Use 'L' prefix to allow pasting in macros
    LDBG = -1,
    LINFO = 0,
    LWARN = 1,
    LERR = 2,
  };
};

/**
 * Signature for log handler callbacks.
 */
typedef void (*LogHandler)(LogLevel::Value level, const std::string& text);

/**
 * Registers a new log handler to be called for logging lines.
 * @param handler Log handler callback invoked on every logged line.
 */
void RegisterLogHandler(LogHandler handler);

/**
 * Registers a logger for dumping to std error.
 */
void RegisterStdErrLogHandler();

/**
 * Stream implementation for logging a single log entry line.
 * Should be invoked using LOG(level) macro.
 * The actual logging happens in destructor.
 */
class LogStream {

  /**
   * Initializes a new log stream with level, file and line.
   */
  public: LogStream(LogLevel::Value level, const std::string& file, int line);

  /**
   * Instructs the logger to throw an runtime_error exception on destruction.
   */
  public: LogStream& SetFatal(const std::string& text)
      { fatal = text; return *this; }

  /**
   * Destructor which does the actual logging from collected data.
   */
  public: virtual ~LogStream();

  /**
   * Bool operator to allow constructs like:
   * condition || LOG(level) << ...
   */
  public: operator bool() { return false; }

  /**
   * Basic stream operators.
   */
  public: LogStream& operator<<(const std::string& text)
      { line << text; return *this; }
  public: LogStream& operator<<(const char* text)
      { line << text; return *this; }
  public: LogStream& operator<<(int number)
      { line << number; return *this; }

  /** Log level. */
  private: LogLevel::Value level;

  /** Fatal flag for triggering runtime_error in destructor. */
  private: std::string fatal;

  /** Log line being constructed. */
  private: std::ostringstream line;
};

////////////////////////////////////////////////////////////////////////
// STL utils.
////////////////////////////////////////////////////////////////////////

template <class Container> void STLDeleteAll(Container* container) {
  for (typename Container::const_iterator it = container->begin();
       it != container->end(); ++it) {
    delete *it;
  }
}

#endif // FILEBOW_COMMON_H__
